package com.samphanie.auiu.common.exception;

import com.samphanie.auiu.common.utils.ApiResponse;
import com.samphanie.auiu.common.utils.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 处理全局异常
 *
 * @author ZSY
 * @createTime 2021/4/19 17:57
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.samphanie.auiu")
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler
    public ApiResponse<?> handleException(ApiException exception) {

        if (exception.getErrorCode() != null) {
            return ApiResponse.failed(exception.getErrorCode());
        } else {
            return ApiResponse.failed(exception.getMessage());
        }

    }

    /**
     * 统一表单验证
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ApiResponse<?> handleNotValidException(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return ApiResponse.failed(ResultCode.VALIDATE_FAILED, errorMap);
    }

}
